package com.changgou.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.config.ConfirmMessageSender;
import com.changgou.seckill.config.RabbitMQConfig;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.service.SecKillOrderService;
import com.changgou.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class SeckillOrderServiceImpl implements SecKillOrderService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ConfirmMessageSender confirmMessageSender;


    @Override
    public boolean add(Long id, String time, String username) {
        //获取商品数据
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + time).get(id);
        String redisStock = (String) redisTemplate.boundValueOps("StockCount_" + seckillGoods.getId()).get();
        if (StringUtils.isEmpty(redisStock)){
            return false;
        }
        int value=Integer.parseInt(redisStock);
        //如果没有库存，则直接抛出异常
        if(seckillGoods==null || value<=0){
            return false;
        }
        //redis预扣库存
        Long stockCount = redisTemplate.boundValueOps("StockCount_" + id).decrement();
        if (stockCount<=0){
            //库存没了
            //删除商品信息
            redisTemplate.boundHashOps("SeckillGoods_" + time).delete(id);
            //删除对应的库存信息
            redisTemplate.delete("StockCount_" + seckillGoods.getId());
        }
        //有库存
        //如果有库存，则创建秒杀商品订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setId(idWorker.nextId());
        seckillOrder.setSeckillId(id);
        seckillOrder.setMoney(seckillGoods.getCostPrice());
        seckillOrder.setUserId(username);
        seckillOrder.setSellerId(seckillGoods.getSellerId());
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setStatus("0");

        //发送消息
        confirmMessageSender.sendMessage("", RabbitMQConfig.SECKILL_ORDER_KEY, JSON.toJSONString(seckillOrder));

        return true;
    }
}
